#include "UdpServ.h"

UdpServ::UdpServ(boost::asio::io_context& ioc)
	:m_socket(ioc, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 10001))
{
	std::cout << "UDP服务启动，监听端口: 10001\n\n";
}

std::shared_ptr<UdpServ> UdpServ::create(boost::asio::io_context& ioc)
{
	return std::shared_ptr<UdpServ>(new UdpServ(ioc));
}

void UdpServ::startRecv()
{
    std::cout << "start recv...\n\n";
	m_socket.async_receive_from(boost::asio::buffer(buff), m_remoteEndpoint,
		[self = shared_from_this()](const boost::system::error_code& ec, size_t bytes)
		{
			self->handleRecv(ec,bytes);
		});
}

void UdpServ::handleRecv(const boost::system::error_code& ec, size_t bytes_transferred)
{
    if (!ec && bytes_transferred > 0)
    {
        // 打印接收信息
        std::cout << "收到来自 " << m_remoteEndpoint.address().to_string()
            << ":" << m_remoteEndpoint.port()
            << " 的 " << bytes_transferred << " 字节数据" << std::endl<<std::endl;

        // 打印前64字节内容（十六进制格式）
        std::cout << "数据: ";
        for (size_t i = 0; i < std::min(bytes_transferred, (size_t)64); ++i) {
            printf("%02x ", static_cast<unsigned char>(buff[i]));
        }
        std::cout << std::endl<<std::endl;

        // 继续接收下个数据包
        startRecv();
    }
    else
    {
        // 错误处理
        if (ec == boost::asio::error::operation_aborted) {
            std::cerr << "接收操作被取消" << std::endl;
        }
        else {
            std::cerr << "接收错误: " << ec.message() << std::endl;

            // 尝试恢复接收（等待1秒后重试）
            auto self = shared_from_this();
            auto timer = std::make_shared<boost::asio::steady_timer>(m_socket.get_executor());
            timer->expires_after(std::chrono::seconds(1));
            timer->async_wait([self, timer](const boost::system::error_code&) {
                self->startRecv();
                });
        }
    }
}
